#include "ask_encode.h"

#include <math.h>

void init_ask_encoder(struct ask_encoder *enc,u_int8_t *bytes,int length,int samplerate,int datarate)
{
	enc->bytes=bytes;
	enc->length=length;

	enc->samplerate=samplerate;
	enc->datarate=datarate;

	enc->samplecount=0;
}

void destroy_ask_decoder(struct ask_encoder *enc)
{
}

int request_ask_output(struct ask_encoder *enc,int16_t *samples,int numsamples)
{
	int totalsamples=total_ask_sample_count(enc);
	int start=enc->samplecount;

	if(start+numsamples>totalsamples) numsamples=totalsamples-start;

	for(int i=0;i<numsamples;i++)
	{
		int bit=(start+i)*enc->datarate/enc->samplerate;
		int value;
		if(bit<252) value=bit&1; // lead-in
		else if(bit<256) value=0; // lead-in end
		else if(bit<256+enc->length*8) // data
		{
			value=enc->bytes[(bit-256)/8]&(1<<(bit%8));
		}
		else value=0; // lead-out

		samples[i]=(int)(32767.0*(value?1.0:0.4)*sin(2*M_PI*(double)(start+i)*(double)enc->datarate/(double)enc->samplerate));
	}

	enc->samplecount+=numsamples;

	return numsamples;
}

int is_ask_done(struct ask_encoder *enc)
{
	int totalsamples=total_ask_sample_count(enc);
	if(enc->samplecount<totalsamples) return 0;
	return 1;
}

int total_ask_sample_count(struct ask_encoder *enc)
{
	return (enc->length*8+2*256)*enc->samplerate/enc->datarate;
}
